<template>
  <view class="menu-list-container">
    <view class="header-section">
      <text class="page-title">菜单管理</text>
    </view>
    
    <view class="toolbar-section">
      <button class="action-button" @click="showCreateMenuModal">创建菜单</button>
    </view>
    
    <view class="menu-tree">
      <view class="menu-item" v-for="menu in menuTree" :key="menu.id">
        <view class="menu-info">
          <text class="menu-name">{{ menu.name }}</text>
          <text class="menu-path">{{ menu.path }}</text>
          <text class="menu-status" :class="menu.status === 1 ? 'status-active' : 'status-inactive'">
            {{ menu.status === 1 ? '启用' : '禁用' }}
          </text>
        </view>
        <view class="menu-actions">
          <button class="action-button small" @click="editMenu(menu)">编辑</button>
          <button class="action-button small danger" @click="deleteMenu(menu)">删除</button>
          <button class="action-button small" @click="toggleMenuStatus(menu)">
            {{ menu.status === 1 ? '禁用' : '启用' }}
          </button>
        </view>
        
        <!-- 子菜单 -->
        <view class="submenu-list" v-if="menu.children && menu.children.length > 0">
          <view class="submenu-item" v-for="submenu in menu.children" :key="submenu.id">
            <view class="submenu-info">
              <text class="submenu-name">├─ {{ submenu.name }}</text>
              <text class="submenu-path">{{ submenu.path }}</text>
              <text class="menu-status" :class="submenu.status === 1 ? 'status-active' : 'status-inactive'">
                {{ submenu.status === 1 ? '启用' : '禁用' }}
              </text>
            </view>
            <view class="submenu-actions">
              <button class="action-button small" @click="editMenu(submenu)">编辑</button>
              <button class="action-button small danger" @click="deleteMenu(submenu)">删除</button>
              <button class="action-button small" @click="toggleMenuStatus(submenu)">
                {{ submenu.status === 1 ? '禁用' : '启用' }}
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="empty-state" v-if="menuTree.length === 0">
      <text class="empty-text">暂无菜单数据</text>
    </view>
    
    <!-- 创建/编辑菜单弹窗 -->
    <view class="modal" v-if="showMenuModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{ isEditMenu ? '编辑菜单' : '创建菜单' }}</text>
          <button class="close-button" @click="closeMenuModal">×</button>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">菜单名称</text>
            <input class="form-input" v-model="menuForm.name" placeholder="请输入菜单名称" />
          </view>
          <view class="form-item">
            <text class="form-label">菜单路径</text>
            <input class="form-input" v-model="menuForm.path" placeholder="请输入菜单路径" />
          </view>
          <view class="form-item">
            <text class="form-label">父级菜单</text>
            <picker mode="selector" :range="parentMenuOptions" @change="onParentMenuChange">
              <view class="form-input">{{ selectedParentMenu || '请选择父级菜单' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">菜单图标</text>
            <input class="form-input" v-model="menuForm.icon" placeholder="请输入图标类名" />
          </view>
          <view class="form-item">
            <text class="form-label">排序</text>
            <input class="form-input" type="number" v-model="menuForm.sort" placeholder="请输入排序值" />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <view class="status-toggle">
              <switch :checked="menuForm.status === 1" @change="onStatusChange" />
              <text class="status-text">{{ menuForm.status === 1 ? '启用' : '禁用' }}</text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closeMenuModal">取消</button>
          <button class="action-button" @click="saveMenu">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { menuApi } from '../../../src/services/system'

// 定义菜单类型
interface Menu {
  id: number
  name: string
  path: string
  parentId: number | null
  icon: string
  sort: number
  status: number
  children?: Menu[]
}

// 菜单树
const menuTree = ref<Menu[]>([])

// 是否显示菜单弹窗
const showMenuModal = ref(false)

// 是否为编辑菜单模式
const isEditMenu = ref(false)

// 当前编辑的菜单
const currentMenu = ref<Menu>({ 
  id: 0, 
  name: '', 
  path: '', 
  parentId: null, 
  icon: '', 
  sort: 0, 
  status: 1 
})

// 菜单表单
const menuForm = ref({
  name: '',
  path: '',
  parentId: null as number | null,
  icon: '',
  sort: 0,
  status: 1
})

// 父级菜单选项
const parentMenuOptions = ref<string[]>(['无'])
const parentMenuList = ref<Menu[]>([])
const selectedParentMenu = ref('')

// 页面加载时获取菜单树
onMounted(() => {
  fetchMenuTree()
})

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    const response: any = await menuApi.getMenuList()
    // 构建菜单树结构
    const menus = response.data
    menuTree.value = buildMenuTree(menus)
    
    // 构建父级菜单选项
    buildParentMenuOptions(menus)
    
    uni.showToast({
      title: '获取菜单列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    uni.showToast({
      title: '获取菜单列表失败',
      icon: 'none'
    })
  }
}

// 构建菜单树结构
const buildMenuTree = (menus: Menu[]): Menu[] => {
  const menuMap = new Map<number, Menu>()
  const roots: Menu[] = []
  
  // 初始化所有菜单
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] })
  })
  
  // 构建父子关系
  menus.forEach(menu => {
    const menuNode = menuMap.get(menu.id)!
    if (menu.parentId === null || menu.parentId === 0) {
      roots.push(menuNode)
    } else {
      const parent = menuMap.get(menu.parentId)
      if (parent) {
        parent.children = parent.children || []
        parent.children.push(menuNode)
      }
    }
  })
  
  return roots
}

// 构建父级菜单选项
const buildParentMenuOptions = (menus: Menu[]) => {
  parentMenuList.value = menus.filter(menu => menu.parentId === null || menu.parentId === 0)
  parentMenuOptions.value = ['无', ...parentMenuList.value.map(menu => menu.name)]
}

// 显示创建菜单弹窗
const showCreateMenuModal = () => {
  isEditMenu.value = false
  menuForm.value = { 
    name: '', 
    path: '', 
    parentId: null, 
    icon: '', 
    sort: 0, 
    status: 1 
  }
  selectedParentMenu.value = '无'
  showMenuModal.value = true
}

// 编辑菜单
const editMenu = (menu: Menu) => {
  isEditMenu.value = true
  currentMenu.value = { ...menu }
  menuForm.value = { ...menu }
  
  // 设置父级菜单选项
  if (menu.parentId) {
    const parent = parentMenuList.value.find(m => m.id === menu.parentId)
    selectedParentMenu.value = parent ? parent.name : '无'
  } else {
    selectedParentMenu.value = '无'
  }
  
  showMenuModal.value = true
}

// 删除菜单
const deleteMenu = async (menu: Menu) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除菜单 "${menu.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await menuApi.deleteMenu(menu.id)
          
          uni.showToast({
            title: '删除菜单成功',
            icon: 'success'
          })
          
          // 重新获取菜单树
          fetchMenuTree()
        } catch (error) {
          console.error('删除菜单失败:', error)
          uni.showToast({
            title: '删除菜单失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 切换菜单状态
const toggleMenuStatus = async (menu: Menu) => {
  try {
    await menuApi.updateMenuStatus(menu.id, { status: menu.status === 1 ? 0 : 1 })
    
    uni.showToast({
      title: `${menu.status === 1 ? '禁用' : '启用'}菜单成功`,
      icon: 'success'
    })
    
    // 重新获取菜单树
    fetchMenuTree()
  } catch (error) {
    console.error('更新菜单状态失败:', error)
    uni.showToast({
      title: '更新菜单状态失败',
      icon: 'none'
    })
  }
}

// 关闭菜单弹窗
const closeMenuModal = () => {
  showMenuModal.value = false
}

// 父级菜单选择变化
const onParentMenuChange = (e: any) => {
  const selectedIndex = e.detail.value
  if (selectedIndex === 0) {
    menuForm.value.parentId = null
    selectedParentMenu.value = '无'
  } else {
    const selectedMenu = parentMenuList.value[selectedIndex - 1]
    menuForm.value.parentId = selectedMenu.id
    selectedParentMenu.value = selectedMenu.name
  }
}

// 状态切换变化
const onStatusChange = (e: any) => {
  menuForm.value.status = e.detail.value ? 1 : 0
}

// 保存菜单
const saveMenu = async () => {
  // 表单验证
  if (!menuForm.value.name) {
    uni.showToast({
      title: '请输入菜单名称',
      icon: 'none'
    })
    return
  }
  
  if (!menuForm.value.path) {
    uni.showToast({
      title: '请输入菜单路径',
      icon: 'none'
    })
    return
  }
  
  try {
    if (isEditMenu.value && currentMenu.value.id) {
      // 编辑菜单
      await menuApi.updateMenu(currentMenu.value.id, menuForm.value)
      
      uni.showToast({
        title: '更新菜单成功',
        icon: 'success'
      })
    } else {
      // 创建菜单
      await menuApi.createMenu(menuForm.value)
      
      uni.showToast({
        title: '创建菜单成功',
        icon: 'success'
      })
    }
    
    // 关闭弹窗
    closeMenuModal()
    
    // 重新获取菜单树
    fetchMenuTree()
  } catch (error) {
    console.error('保存菜单失败:', error)
    uni.showToast({
      title: '保存菜单失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.menu-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.toolbar-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  text-align: right;
}

.action-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  
  &.small {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }
  
  &.danger {
    background-color: #f44336;
  }
  
  &.cancel {
    background-color: #999;
  }
}

.menu-tree {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.menu-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.menu-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.menu-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.menu-path {
  font-size: 28rpx;
  color: #666;
}

.menu-status {
  font-size: 24rpx;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
}

.status-active {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-inactive {
  background-color: #ffebee;
  color: #f44336;
}

.menu-actions {
  display: flex;
  gap: 10rpx;
  justify-content: flex-end;
}

.submenu-list {
  margin-top: 20rpx;
  padding-left: 30rpx;
  border-left: 2rpx solid #f5f5f5;
}

.submenu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.submenu-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.submenu-name {
  font-size: 28rpx;
  color: #333;
}

.submenu-path {
  font-size: 24rpx;
  color: #666;
}

.submenu-actions {
  display: flex;
  gap: 10rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
  padding: 0;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;
}

.status-toggle {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.status-text {
  font-size: 28rpx;
  color: #333;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 2rpx solid #f5f5f5;
}
</style>